package com.hhhn.wk.login.perfect;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.login.CheckActivity;
import com.hhhn.wk.login.RegisterActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.AppValidationMgr;
import com.hhhn.wk.utils.MD5Util;
import com.hhhn.wk.utils.mi.AES;
import com.hhhn.wk.widget.dialog.AddressDialog01;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 完 善 资 料
 */
public class PerfectActivity extends BaseActivity {

    ArrayList<Adress> adresses01=new ArrayList<>();
    ArrayList<Adress> adresses02=new ArrayList<>();
    ArrayList<Adress> adresses03=new ArrayList<>();
    Adress mAdress1=null;
    Adress mAdress2=null;
    Adress mAdress3=null;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;
    private boolean mBackKeyPressed = false;
    private EditText et_username;//店主姓名
    private EditText et_name;//店面名称
    private EditText et_address;//店面详细地址
    private EditText et_staff;//员工ID
    private TextView et_address_province;//省
    private TextView et_address_city;//市
    private TextView et_address_county;//区
    private LinearLayout ll_login;//立即完善
    private Context context;
    private BaseActivity activity;
    String id01="";
    String id02="";
    String id03="";
    Handler handler=new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    AddressDialog01.showSheet(context, "请选择您的省份", adresses01, new AddressDialog01.OnActionSheetSelected() {
                        @Override
                        public void onClick(int whichButton, String id, String name) {
                            Log.e("##", "id: "+id);
                            id01=id;
                            et_address_province.setText(name);
                            Log.e("##", "name: "+name);
                        }
                    }, new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialogInterface) {

                        }
                    });
                    break;
                case 2:
                    AddressDialog01.showSheet(context, "请选择您的城市", adresses02, new AddressDialog01.OnActionSheetSelected() {
                        @Override
                        public void onClick(int whichButton, String id, String name) {
                            Log.e("##", "id: "+id);
                            id02=id;
                            Log.e("##", "name: "+name);
                            et_address_city.setText(name);
                        }
                    }, new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialogInterface) {

                        }
                    });
                    break;
                case 3:
                    AddressDialog01.showSheet(context, "请选择您的县域", adresses03, new AddressDialog01.OnActionSheetSelected() {
                        @Override
                        public void onClick(int whichButton, String id, String name) {
                            Log.e("##", "id: "+id);
                            id03=id;
                            Log.e("##", "name: "+name);
                            et_address_county.setText(name);
                        }
                    }, new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialogInterface) {

                        }
                    });
                    break;
            }
        }
    };
    String userId="";
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_perfect);
        context=PerfectActivity.this;
        activity=this;
        Intent intent=getIntent();
         userId = intent.getStringExtra("userId");
    }
    @Override
    protected void initView() {
        et_username=findViewById(R.id.et_username);
        et_name=findViewById(R.id.et_name);
        et_address=findViewById(R.id.et_address);
        ll_login=findViewById(R.id.ll_login);
        et_address_province=findViewById(R.id.et_address_province);
        et_address_city=findViewById(R.id.et_address_city);
        et_address_county=findViewById(R.id.et_address_county);
        et_staff=findViewById(R.id.et_staff);
    }
    @Override
    protected void initData() {
    }
    @Override
    protected void initClick() {
        ll_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                judge();
            }
        });
        et_address_province.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adresses01.clear();
                adresses02.clear();
                adresses03.clear();

                getAdrees01();
            }
        });
        et_address_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adresses01.clear();
                adresses02.clear();
                adresses03.clear();
                getAdrees02(id01);
            }
        });
        et_address_county.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adresses01.clear();
                adresses02.clear();
                adresses03.clear();
                getAdrees03(id02);
            }
        });
    }
    //判断
    private void  judge(){
        String str_username = et_username.getText().toString().trim();
        String str_name = et_name.getText().toString().trim();
        String str_address = et_address.getText().toString().trim();
        String str_address_province = et_address_province.getText().toString().trim();
        String str_address_city = et_address_city.getText().toString().trim();
        String str_address_county = et_address_county.getText().toString().trim();
        if (str_username==null||"".equals(str_username)){
            toastWk("请输入店主姓名");
            return;
        }
        if (str_name==null||"".equals(str_name)){
            toastWk("请输入店铺名称");
            return;
        }
        if (str_address==null||"".equals(str_address)){
            toastWk("请输入店铺地址");
            return;
        }

//
//        int result1 = str_address.indexOf("王鲁镇");
//        int result1 = str_address.indexOf("a");
//        int result1 = str_address.indexOf("a");
//        int result1 = str_address.indexOf("a");
//        int result1 = str_address.indexOf("a");
//        int result1 = str_address.indexOf("a");
//        if(result1 != -1 ){
//            System.out.println("字符串str中包含子串“a”"+result1);
//        }else{
//            System.out.println("字符串str中不包含子串“a”"+result1);




        if (str_address_province==null||"".equals(str_address_province)||"请选择您所在的省份".equals(str_address_province)){
            toastWk("请选择省份");
        return;
        }
        if (str_address_city==null||"".equals(str_address_city)||"请选择您所在的城市".equals(str_address_city)){
            toastWk("请选择城市");
            return;
        }
        if (str_address_county==null||"".equals(str_address_county)||"请选择您所在的县域".equals(str_address_county)){
            toastWk("请选择县域");
            return;
        }
        /**
         * 吊起后台接口
         */
        getRegister();
    }
    //完 善 资 料
    public void getRegister() {
        showLoad();
        RequestParams params = AllPublic.getParamsAccount(activity, "/registerInfo", false);
//        params.addParameter("realName",et_username.getText().toString().trim());/*店铺名称*/
//        params.addParameter("shopName",et_name.getText().toString().trim());/*店铺名称*/
//        params.addParameter("address",et_address.getText().toString().trim());/*店铺地址*/
//        params.addParameter("mangerId",et_staff.getText().toString().trim());/*业务id*/
//        params.addParameter("id",userId);/*用户id*/
//
//        params.addParameter("province",id01);/*省*/
//        params.addParameter("city",id02);/*市*/
//        params.addParameter("town",id03);/*县*/
        try {
            JSONObject person=new JSONObject();
            person.put("realName",et_username.getText().toString().trim());/*店铺名称*/
            person.put("shopName",et_name.getText().toString().trim());/*店铺名称*/
            person.put("address",et_address.getText().toString().trim());/*店铺地址*/
            person.put("mangerId",et_staff.getText().toString().trim());/*业务id*/
            person.put("id",userId);/*用户id*/

            person.put("province",id01);/*省*/
            person.put("city",id02);/*市*/
            person.put("town",id03);/*县*/

            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {

                        toastWk("完 善 成 功");
                        Intent intent=new Intent(context,CheckActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogWk("完 善 资 料-第二个："+ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                LogWk("完 善 资 料-第三个：");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                LogWk("完 善 资 料-第四个：");
                dismissLoad();
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!mBackKeyPressed) {
                mBackKeyPressed = true;
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        mBackKeyPressed = false;
                    }
                }, 20);
                return true;
            } else {
                this.finish();
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 获取省
     */
    public void getAdrees01(){
        showLoad();
        RequestParams params = AllPublic.getParamsShipAddress(activity, "/province", false);
        params.addParameter("parentId",0);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                LogWk("获取省:"+result);
                try {
                    JSONObject result1= new JSONObject(result);
                    String reason = result1.getString("code");
                    if (reason.equals("0")) {
                        JSONArray data = result1.getJSONArray("data");
                        for (int i=0;i<data.length();i++){
                            mAdress1=new Adress();
                            JSONObject jsonObject = data.getJSONObject(i);
                            String itemId = jsonObject.has("itemId") ? jsonObject.getString("itemId") : "";
                            String areaname = jsonObject.has("areaname") ? jsonObject.getString("areaname") : "";
                            mAdress1.setId(itemId);
                            mAdress1.setName(areaname);
                            adresses01.add(mAdress1);
                        }
                        handler.sendEmptyMessage(1);
                        dismissLoad();
                    }else {
                        toastWk(result1.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogWk("获取省-第二个："+ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                LogWk("获取省-第三个：");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                LogWk("获取省-第四个：");
                dismissLoad();
            }
        });
    }
    /**
     * 获取市
     */
    public void getAdrees02(String id){
        showLoad();
        RequestParams params = AllPublic.getParamsShipAddress(activity, "/province", false);
        params.addParameter("parentId",id);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                LogWk("获取市:"+result);
                try {
                    JSONObject result1= new JSONObject(result);
                    String reason = result1.getString("code");
                    if (reason.equals("0")) {
                        JSONArray data = result1.getJSONArray("data");
                        for (int i=0;i<data.length();i++){
                            mAdress2=new Adress();
                            JSONObject jsonObject = data.getJSONObject(i);
                            String itemId = jsonObject.has("itemId") ? jsonObject.getString("itemId") : "";
                            String areaname = jsonObject.has("areaname") ? jsonObject.getString("areaname") : "";
                            mAdress2.setId(itemId);
                            mAdress2.setName(areaname);
                            adresses02.add(mAdress2);
                        }
                        handler.sendEmptyMessage(2);
                        dismissLoad();
                    }else {
                        toastWk(result1.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogWk("获取市-第二个："+ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                LogWk("获取市-第三个：");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                LogWk("获取市-第四个：");
                dismissLoad();
            }
        });
    }
    /**
     * 获取县
     */
    public void getAdrees03(String id){
        showLoad();
        RequestParams params = AllPublic.getParamsShipAddress(activity, "/province", false);
        params.addParameter("parentId",id);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                LogWk("获取县:"+result);
                try {
                    JSONObject result1= new JSONObject(result);
                    String reason = result1.getString("code");
                    if (reason.equals("0")) {
                        JSONArray data = result1.getJSONArray("data");
                        for (int i=0;i<data.length();i++){
                            mAdress3=new Adress();
                            JSONObject jsonObject = data.getJSONObject(i);
                            String itemId = jsonObject.has("itemId") ? jsonObject.getString("itemId") : "";
                            String areaname = jsonObject.has("areaname") ? jsonObject.getString("areaname") : "";
                            mAdress3.setId(itemId);
                            mAdress3.setName(areaname);
                            adresses03.add(mAdress3);
                        }
                        handler.sendEmptyMessage(3);
                        dismissLoad();
                    }else {
                        toastWk(result1.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogWk("获取县-第二个："+ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                LogWk("获取县-第三个：");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                LogWk("获取县-第四个：");
                dismissLoad();
            }
        });
    }
}
